package com.lanxin.jet.controllers;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lanxin.jet.beans.UserBean;
import com.lanxin.jet.mappers.UserMapper;
import com.lanxin.jet.services.UserService;
import com.lanxin.jet.tools.JetDate;
import com.lanxin.jet.tools.JetResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/admin")
@Controller
public class AdminController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录 - 页面
     */
    @RequestMapping("loginPage")
    public String loginPage() {
        return "admin/login";
    }

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request) {
        JetResponse jr = new JetResponse();
        String account = request.getParameter("account");
        String password = DigestUtils.md5DigestAsHex(request.getParameter("password").trim().getBytes());
        if (! account.isEmpty()) {
            UserBean user = userMapper.queryByAccount(account);
            if (user != null && password.equals(user.getPassword()) && user.getStatus() == UserService.STATUS_ADMIN) {
                //缓存会话
                HttpSession session = request.getSession();
                session.setAttribute("uid", user.getId());
                session.setAttribute("role", user.getRole());
                session.setAttribute("name", user.getName());
                session.setAttribute("activeTime", JetDate.date(user.getActiveTime(), "yyyy-MM-dd HH:mm"));
                session.setAttribute("ip", user.getIp());
                //更新登录记录
                user.setIp(request.getRemoteAddr());
                user.setActiveTime(JetDate.timeNow());
                userMapper.update(user);
                jr.success();
            } else {
                jr.error(JetResponse.RES_FAIL, "账号不存在或者不是管理员");
            }
        } else {
            jr.error(JetResponse.RES_PARAMF, "账号不能空");
        }
        return jr.map();
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("uid");
        session.removeAttribute("role");
        session.removeAttribute("name");
        session.removeAttribute("activeTime");
        session.removeAttribute("ip");
        try {
            response.sendRedirect("/admin/loginPage");
        } catch (IOException e) {
            //e.printStackTrace();
        }
    }
}